package com.gljx.web.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.gljx.constant.Constant;
import com.gljx.shiro.passwordEncrypt.PasswordHelper;
import com.gljx.util.CommonUtil;
import com.gljx.util.ResourceUtil;
import com.gljx.web.dao.UserMapper;
import com.gljx.web.Entity.User;
import com.gljx.web.service.UserService;

@Service
@Transactional
public class UserServiceImpl implements UserService{
	
	@Autowired
	private UserMapper userDao;

	private String defaultPwd = ResourceUtil.getProper("password.default");
	@Override
	public String setUserPwd(String pwd, String newPwd) {
		
		//从令牌获取账号 然后获取对应用户数据
		String number = (String)SecurityUtils.getSubject().getPrincipal();
		User user = userDao.selectByPrimaryKey(number,Constant.Project_ID);
		if(user == null){
			return "请刷新重试";
		}
		
		//=======密码比对======
		String oldPwd = user.getPassword();
		user.setPassword(pwd);
		
		user = PasswordHelper.encryptPassword(user);//加密
		
		//数据库与前台密码一致
		if(oldPwd.equals(user.getPassword())){
			user.setOldPassword(oldPwd);
			user.setPassword(newPwd);
			user = PasswordHelper.encryptPassword(user);
			return userDao.userSetPassWord(user)>0?"success":"密码不正确";
		}else{
			return "密码不正确";
		}
		
	}

	@Override
	public Map <String,Object > selectBIUser(String rows,
											String page,
											String name,		//姓名
											String dept,		//部门
			    		     				String company,		//公司
			    		     				String fisAdmin,	//是否管理
			    		     				String fisPower,	//是否授权
			    		     				String fisDelete,	//是否可用
			    		     				String fisProjecjt) {
		Integer pageNum = Integer.valueOf(page);
		Integer pageSize = Integer.valueOf(rows);
		Map <String,Object > data = new HashMap<String, Object>();
		data.put("Pindex", pageNum);
		
		String sql=  "select ug.fname_l2 deptName,c.flongnumber CompanyLongFnumber,"
						+ "u.fgroupid deptId,u.ID, u.FID,c.fname_l2 companyName, "
						+ "u.USER_NAME, u.NAME, u.PASSWORD, "
						+ "u.FIS_DELETE,u.FIS_ADMIN, u.FCOMPANYID, u.CREAT_TIME,u.UPDATE_TIME, "
						+ "u.CREAT_ID, u.UPDATE_ID, u.REMARK, u.FIS_POWER, u.FTYPE  ,p.userid fisproject from t_e_user u "
							+"left join T_ORG_Company c on c.fid(+) = u.fcompanyid  "
							+ " left join t_pm_usergroup ug on ug.fid = u.fgroupid "
							+ "left join  "
								+"( select s.projectsubid userid from t_p_sub s "
								+ "where s.projectnumber = '"+Constant.Project_ID+"' and s.subtype = 1) p"
							+" on p.userid = u.id where 1 = 1 ";
		
		if(name != null && !"".equals(name)){
			sql+= " and u.NAME like '%"+name+"%'" ;//姓名
		}
		if(company != null && !"".equals(company)){
			sql+= " and c.fname_l2 like'%"+company+"%'" ;//公司
		}
		if(dept!= null &&!"".equals(dept)){
			sql+= " and ug.fname_l2 like'%"+dept+"%'" ;//部门
		}
		if(!"no".equals(fisAdmin)){
			sql+= " and u.fis_admin ="+fisAdmin ;
		}
		if(!"no".equals(fisPower)){
			sql+= " and u.fis_power ="+fisPower ;
		}
		if(!"no".equals(fisDelete)){
			sql+= " and u.fis_delete = "+fisDelete ;
		}
		if(!"no".equals(fisProjecjt)){
			if("0".equals(fisProjecjt)){
				sql+= " and p.userid is null " ;
			}else{
				sql+= " and p.userid is not null " ;
			}
				
		}
		data.put("Psql",sql);
		data.put("Psize", pageSize);
		userDao.selectBIUser(data);
		return data;
	}

	@Override
	public String insert(User user) throws IllegalAccessException {
		
		Session session = SecurityUtils.getSubject().getSession();
		//session中的当前用户账户和公司ID
		user.setCreatId((String)SecurityUtils.getSubject().getPrincipal());
		if(user.getFcompanyid() == null){
			user.setFcompanyid((String)session.getAttribute
					(Constant.CompanyId_session));
		}
		//插入时间 、默认设置为已授权用户
		user.setCreatTime(CommonUtil.nowTime());
		user.setFisPower(1);
		user.setFisDelete(0);
		user.setPassword(defaultPwd);
		
		Map <String,Object > data = CommonUtil.objectToMap(user, "v_",
				Arrays.asList(new String[] { "id","serialVersionUID","companyName","fisDelete","updateTime","updateId", "updateTime","oldPassword" }));
		
		userDao.insertUser(data);
		user.setId((Integer)data.get("v_id"));
		//加密密码
		user = PasswordHelper.encryptPassword(user);
		
		this.updateUser(user);
		
		return this.updateUser(user);//userDao.insertSelective(user)>0?"success":"未知异常";
	}
	public String updateUser(User user){
		user.setUpdateId((String)SecurityUtils.getSubject().getPrincipal());
		user.setUpdateTime(CommonUtil.nowTime());
		return userDao.updateUser(user)>0?"success":"未找到用户";
	}

	@Override
	public Integer powerUser(String ids) {
		String[] idStrings = ids.split(",");
		List<User> users = new ArrayList<User>();
		String updateId = (String)SecurityUtils.getSubject().getPrincipal();
		//加入user集合
		for(String string : idStrings){
			String [] idAndName = string.split("!!!");
			User user = new User();
			//ID和账户
			user.setId(Integer.valueOf(idAndName[0]));
			user.setUserName(idAndName[1]);
			//修改人和修改时间
			user.setUpdateTime(CommonUtil.nowTime());
			user.setUpdateId(updateId);
			//密码加密
			user = PasswordHelper.encryptPassword(user);
			
			users.add(user);
		}
		return userDao.powerUser(users);
	}
	
	@Override
	public Integer setProject(String ids,String flag) {
		String[] idStrings = ids.split(",");
		List<User> users = new ArrayList<User>();
		for(String string : idStrings){
			User user = new User();
			//ID和账户
			user.setId(Integer.valueOf(string));
			//修改人和修改时间
			user.setUpdateTime(CommonUtil.nowTime());
			user.setUpdateId((String)SecurityUtils.getSubject().getPrincipal());
			
			users.add(user);
		}
		//如果0删除相关数据，否则插入
		Integer result = 0;
		if("0".equals(flag)){
			result = userDao.deleteProject(users,Constant.Project_ID);
			userDao.updateUpdateId(users);
		}else if ("1".equals(flag)){
			result = userDao.setProject(users,Constant.Project_ID);
			userDao.updateUpdateId(users);
		}
		return result;
	}
	
	public User selectUserData(Integer id){
		return userDao.selectUserData(id,Constant.Project_ID);
	}

	@Override
	public List<Map<String, Object>> findHandle(Integer id, String menuName, String PID, String name) {
		return userDao.findHandle(id, menuName, PID, name);
	}
	@Override
	public List<User> queryUserTypeByCompanyId(String fcompanyid) {
		return userDao.queryUserTypeByCompanyId(fcompanyid);
	}
	@Override
	public List<User> selectUserByNameForJournal(Map<String, Object> map) {
		return userDao.selectUserByNameForJournal(map);
	}
	@Override
	public List<User> queryUserByCompanyId(String companyId) {
		return userDao.selectUserByCompanyId(companyId);
	}
	@Override
	public User queryUserByFid(String fid) {
		return userDao.selectUserByFid(fid);
	}
	@Override
	public List<User> queryUserByCompanyIdAndName(String companyId,String name) {
		Map<String, String> map = new HashMap<>();
		map.put("companyId", companyId);
		map.put("name", name);
		return userDao.selectUserByCompanyIdAndName(map);
	}
}
